package com.wxq.workpad.base

import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.wxq.workpad.utils.ApplicationUtils
import com.wxq.workpad.utils.FontUtils
import com.wxq.workpad.utils.autosize.AutoSizeHelper
import com.wxq.workpad.widget.LoadingUtils
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type


abstract class BaseActivity<VB : ViewBinding> :AppCompatActivity() {


    lateinit var binding: VB
    lateinit var mContext:Context

//     var mIsUseAutoSize:Boolean=true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = this
        initViewBinding()

        //初始化控件
        initView(savedInstanceState)
        //初始化数据
        initData()
    }

    abstract fun initData()

    abstract fun initView(instanceState: Bundle?)

    private fun initViewBinding() {
        val superclass: Type = javaClass.genericSuperclass
        val aClass = (superclass as ParameterizedType).getActualTypeArguments().get(0) as Class<*>
        val method: Method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(null, layoutInflater) as VB
        setContentView(binding.root)
    }


    // 是否需要autosize 默认需要
    open  fun isNeedAutoSize():Boolean{
         return true
    }

    override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
        if (isNeedAutoSize()) {
            val initDensity: Float = AutoSizeConfig.getInstance().getInitDensity()
            //如果开启了AutoSize，并且当前density与初始时density相同，则说明适配失效（比如因为webview），重新适配
            if (resources.displayMetrics.density == initDensity) {
                AutoSizeHelper.judgeAndFitWidth()
                AutoSizeHelper.resetScreenSize(this)
                AutoSize.autoConvertDensityOfGlobal(this)
            }
        }
//        FontUtils.setScaleFont(context.resources)

        FontUtils.setScaleFont(context.resources)
        return super.onCreateView(name, context, attrs)
    }

    fun showToast(it:String){
        Toast.makeText(ApplicationUtils.getTopActivity(), it, Toast.LENGTH_SHORT).show()
    }



    private val dialogUtils by lazy {
        LoadingUtils(this)
    }
    /**
     * 加载提示框
     */
    fun showLoading() {
        dialogUtils.showLoading("加载中")
    }

    /**
     * 关闭提示框
     */
    fun dismissLoading() {
        dialogUtils.dismissLoading()
    }
}